﻿/*
[]
*/

Ext.namespace("tk","tk.yunos","tk.yunos.app");

tk.yunos.app.TextViewer = function(fileDescriptor, config){
	var panel = new tk.yunos.app.TextViewer.Panel(fileDescriptor, config);
	var winParams = {
		title: tk.yunos.app.TextViewer.appname + '[' + fileDescriptor.address + ']',
		icon: fileDescriptor.icon,
		layout: 'fit',
		items: [
		    panel
		]
	};
	tk.yunos.system.GLOBAL_WINDOWMGR.newWindow(winParams).show();
};

tk.yunos.app.TextViewer.Panel = function(fileDescriptor, config){
	var textViewer = this;
	
	var textContainer;
	var fontSize = 14;
	var step = 2;
	
	this.load = function(file){
		if(textViewer.getWindow && textViewer.getWindow()){
			textViewer.getWindow().wait();
		}
		tk.yunos.filesystem.getFileContent(file.address, function(success, fileContent){
			if(success){
				if(textContainer){
					Ext.get(textContainer).remove();
				}
				textContainer = document.createElement('pre');
				textContainer.innerHTML = prettyPrintOne(formatCode(fileContent), null, true);
				textContainer.style.fontSize = fontSize + 'px';
				contentArea.body.appendChild(textContainer);
			}
			if(textViewer.getWindow && textViewer.getWindow()){
				textViewer.getWindow().finish();
			}
		});
	};
	
	this.refresh = function(){
		textViewer.load(fileDescriptor);
	};
	
	var contentArea = new Ext.Panel({
		region: 'center',
		border: false,
		bodyStyle: 'overflow:auto;padding: 5px 5px 5px 5px',
		listeners: {
			'render': function(panel){
				if(fileDescriptor){
					textViewer.load(fileDescriptor);
				}
			}
		}
	});
	
	//替换代码中的特殊字符
	function formatCode(code){
		return code.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
	}
	
	config = config || {};
	config.layout = 'border';
	config.items = [contentArea];
	config.tbar = new Ext.Toolbar({
		items: [{
			'text': '字体',
			iconCls: 'increase',
			handler: function(){
				fontSize += step;
				if(textContainer){
					textContainer.style.fontSize = fontSize + 'px';
					Ext.get(textContainer).repaint();
				}
			}
		},'-',{
			'text': '字体',
			iconCls: 'decrease',
			handler: function(){
				if(fontSize > step){
					fontSize -= step;
				}
				if(textContainer){
					textContainer.style.fontSize = fontSize + 'px';
					Ext.get(textContainer).repaint();
				}
			}
		}]
	});
	
	Ext.apply(this, config);
	//调用父类构造方法
	tk.yunos.app.TextViewer.Panel.superclass.constructor.call(this, config);
};

Ext.extend(tk.yunos.app.TextViewer.Panel, Ext.Panel, {
	border: false
});

tk.yunos.app.TextViewer.appname = '文本查看器';